package com.ssy.lingxi.order.serviceimpl.paas;

import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.order.api.model.vo.paas.OrderPayChannelFeignVO;
import com.ssy.lingxi.order.api.model.vo.paas.OrderRuleFeignVO;
import com.ssy.lingxi.order.entity.BaseOrderPayChannelDO;
import com.ssy.lingxi.order.entity.BaseOrderRuleDO;
import com.ssy.lingxi.order.repository.BaseOrderPayChannelRepository;
import com.ssy.lingxi.order.repository.BaseOrderRuleRepository;
import com.ssy.lingxi.order.service.paas.IOrderConfigService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 订单服务同步配置实现类
 * @author 万宁
 * @version 2.0.0
 * @date 2021-08-04
 */
@Service
public class OrderConfigServiceImpl implements IOrderConfigService {
    @Resource
    private BaseOrderRuleRepository baseOrderRuleRepository;

    @Resource
    private BaseOrderPayChannelRepository baseOrderPayChannelRepository;

    /**
     * 同步更新订单类型、订单模式状态
     *
     * @param rules 接口参数
     * @return 更新结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> updateOrInsertOrderRules(List<OrderRuleFeignVO> rules) {
        List<BaseOrderRuleDO> orderRules = baseOrderRuleRepository.findAll();
        //修改状态
        orderRules.forEach(orderRule -> rules.stream().filter(rule -> rule.getRuleType().equals(orderRule.getRuleType()) && rule.getMethodCode().equals(orderRule.getMethodCode())).findFirst().ifPresent(rule -> orderRule.setStatus(rule.getStatus())));

        baseOrderRuleRepository.saveAll(orderRules);
        return Wrapper.success();
    }

    /**
     * 同步更新支付方式与支付渠道状态
     *
     * @param payChannels 接口参数
     * @return 更新结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Wrapper<Void> updateOrderPayChannelStatus(List<OrderPayChannelFeignVO> payChannels) {
        List<BaseOrderPayChannelDO> baseOrderPayChannels = baseOrderPayChannelRepository.findAll();
        baseOrderPayChannels.forEach(baseOrderPayChannel -> payChannels.stream().filter(payChannel -> payChannel.getPayType().equals(baseOrderPayChannel.getPayType()) && payChannel.getPayChannel().equals(baseOrderPayChannel.getPayChannel())).findFirst().ifPresent(payChannel -> baseOrderPayChannel.setStatus(payChannel.getStatus())));

        baseOrderPayChannelRepository.saveAll(baseOrderPayChannels);
        return Wrapper.success();
    }
}
